package com.itheima.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.ResourceMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Resource;
import com.itheima.pojo.User;
//import jxl.Workbook;
//import org.apache.poi.ss.usermodel.Workbook;
import com.itheima.utils.ExcelExportEngine;
import com.opencsv.CSVWriter;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.Units;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;


import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ResourceMapper resourceMapper;
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ss");

    public List<User> findAll() {
        return userMapper.selectAll();
    }

    public User findById(Long id) {
        //查询用户
        User user = userMapper.selectByPrimaryKey(id);
        //根据用户id查询办公用品
        Resource resource = new Resource();
        resource.setUserId(id);
        List<Resource> resourceList = resourceMapper.select(resource);
        user.setResourceList(resourceList);
        return user;
    }

    public List<User> findPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);  //开启分页
        Page<User> userPage = (Page<User>) userMapper.selectAll(); //实现查询
        return userPage.getResult();
    }

    public void downLoadXlsByJxl(HttpServletResponse response) throws IOException, WriteException {
        // 创建一个工作簿
        ServletOutputStream outputStream = response.getOutputStream();
        WritableWorkbook workbook = Workbook.createWorkbook(outputStream);
        // 创建一个工作表
        WritableSheet sheet = workbook.createSheet("Jxl入门", 0);
        // 设置列宽
        sheet.setColumnView(0,5);
        sheet.setColumnView(1,8);
        sheet.setColumnView(2,15);
        sheet.setColumnView(3,15);
        sheet.setColumnView(4,30);

        // 处理标题
        String[] titles = new String[]{"编号","姓名","手机号","入职日期","现住址"};
        Label label = null;
        for (int i = 0; i < titles.length; i++) {
            label = new Label(i,0,titles[i]);
            sheet.addCell(label);
        }
        // 处理导出的内容
        List<User> userList = this.findAll();
        int rowIndex = 1;
        for (User user : userList) {
            label = new Label(0,rowIndex,user.getId().toString());
            sheet.addCell(label);

            label = new Label(1,rowIndex,user.getUserName().toString());
            sheet.addCell(label);

            label = new Label(2,rowIndex,user.getPhone().toString());
            sheet.addCell(label);

            label = new Label(3,rowIndex,sdf.format(user.getHireDate()).toString());
            sheet.addCell(label);

            label = new Label(4,rowIndex,user.getAddress().toString());
            sheet.addCell(label);

            rowIndex ++;
        }

        // 导出的文件名称 低版本一个流两个头
        String fileName = "一个JXL入门.xls";
        // 设置文件的打开方式和mime类型
        response.setHeader( "Content-Disposition", "attachment;filename="  + new String(fileName.getBytes(),"ISO8859-1"));
        response.setContentType("application/vnd.ms-excel");
        // 导出
        workbook.write();
        // 关闭资源
        workbook.close();
        outputStream.close();
    }

    public void uploadExcel(MultipartFile file) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //根据上传的输入流创建workbook
        XSSFWorkbook workBook = new XSSFWorkbook(file.getInputStream());
        //获取工作薄中的第一个工作表
        XSSFSheet sheet = workBook.getSheetAt(0);
        //获取这个sheet中最后一行数据，为了循环遍历
        int lastRowNum = sheet.getLastRowNum();
        //开始循环每行，获取每行的单元格中的值，放入到user属性中
        for (int i = 1; i <= lastRowNum; i++) {
            User  user = new User();
            XSSFRow row = sheet.getRow(i);
            // 不为空列数
            int numberOfCells = row.getPhysicalNumberOfCells();
            String userName = row.getCell(0).getStringCellValue();
            String telPhone = "";
            try {
                telPhone = row.getCell(1).getStringCellValue();
            } catch (Exception e) {
                telPhone = row.getCell(1).getNumericCellValue()+"";
            }
            String province = row.getCell(2).getStringCellValue();
            String city = row.getCell(3).getStringCellValue();
            int salary = 0;
            try {
//                salary = ((Double)row.getCell(4).getNumericCellValue()).intValue();  // 写法一
                XSSFCell cell = row.getCell(4);
                cell.setCellType(CellType.STRING);
                String salaryStr = cell.getStringCellValue();
                salary = Integer.parseInt(salaryStr);
            } catch (Exception e) {
                salary = Integer.parseInt(row.getCell(4).getStringCellValue());
            }
            Date hireDate  = sdf.parse(row.getCell(5).getStringCellValue());
            Date birthDay  = sdf.parse(row.getCell(6).getStringCellValue());
            String address = row.getCell(7).getStringCellValue();

            user.setUserName(userName);
            user.setPhone(telPhone);
            user.setProvince(province);
            user.setCity(city);
            user.setSalary(salary);
            user.setHireDate(hireDate);
            user.setBirthday(birthDay);
            user.setAddress(address);

            userMapper.insert(user);
        }
    }

    public void downLoadXlsxByPoi(HttpServletResponse response) throws Exception{
        // 创建一个工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 在工作簿中创建一个工作表
        XSSFSheet sheet = workbook.createSheet("用户数据");
        // 设置列宽
        sheet.setColumnWidth(0,5*256);
        sheet.setColumnWidth(1,8*256);
        sheet.setColumnWidth(2,15*256);
        sheet.setColumnWidth(3,15*256);
        sheet.setColumnWidth(4,30*256);

        // 处理标题
        String[] titles = new String[]{"编号","姓名","手机号","入职日期","现住址"};
        // 创建标题行
        XSSFRow row = sheet.createRow(0);
        for (int i = 0; i < titles.length; i++) {
            XSSFCell cell = row.createCell(i);
            cell.setCellValue(titles[i]);
        }
        // 处理内容
        List<User> userList = this.findAll();
        int rowIndex = 1;
        for (User user : userList) {
            XSSFRow sheetRow = sheet.createRow(rowIndex);

            XSSFCell cell1 = sheetRow.createCell(0);
            cell1.setCellValue(user.getId());

            XSSFCell cell2 = sheetRow.createCell(1);
            cell2.setCellValue(user.getUserName());

            XSSFCell cell3 = sheetRow.createCell(2);
            cell3.setCellValue(user.getPhone());

            XSSFCell cell4 = sheetRow.createCell(3);
            cell4.setCellValue(sdf.format(user.getHireDate()));

            XSSFCell cell5 = sheetRow.createCell(4);
            cell5.setCellValue(user.getAddress());

            rowIndex ++;
        }
//        导出的文件名称  高版本一个流两个头
        String filename="员工数据.xlsx";
        //            设置文件的打开方式和mime类型
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader( "Content-Disposition", "attachment;filename="  + new String(filename.getBytes(),"ISO8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        workbook.write(outputStream);
    }

    public void downLoadXlsxByPoiWithCellStyle(HttpServletResponse response) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("有样式的数据");
        // 设置列宽
        sheet.setColumnWidth(0,5*256);
        sheet.setColumnWidth(1,8*256);
        sheet.setColumnWidth(2,15*256);
        sheet.setColumnWidth(3,16*256);
        sheet.setColumnWidth(4,30*256);
        // 需求： 边框线 行高 合并单元格 对齐方式 字体
        XSSFCellStyle bigTitleRowCellStyle = workbook.createCellStyle();

        bigTitleRowCellStyle.setBorderBottom(BorderStyle.THIN);  // 下边框   thin细线
        bigTitleRowCellStyle.setBorderLeft(BorderStyle.THIN);
        bigTitleRowCellStyle.setBorderRight(BorderStyle.THIN);
        bigTitleRowCellStyle.setBorderTop(BorderStyle.THIN);
        // 对齐方式 水平居中，垂直居中
        bigTitleRowCellStyle.setAlignment(HorizontalAlignment.CENTER);  // 水平居中
        bigTitleRowCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        // 创建字体
        XSSFFont font = workbook.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short) 18);
        // 把字体放入样式中
        bigTitleRowCellStyle.setFont(font);

        XSSFRow bigTitleRow = sheet.createRow(0);
        bigTitleRow.setHeightInPoints(42);  // 设置行高
        for (int i = 0; i < 5; i++) {
            XSSFCell cell = bigTitleRow.createCell(i);
            cell.setCellStyle(bigTitleRowCellStyle);
        }
        sheet.addMergedRegion(new CellRangeAddress(0,0,0,4));  // int firstRow 起始行, int lastRow 结束行, int firstCol 起始列, int lastCol 结束列
        // 第一行插入数据
        sheet.getRow(0).getCell(0).setCellValue("用户信息数据");

        // 小标题
        XSSFCellStyle littleTitleRowCellStyle = workbook.createCellStyle();
        littleTitleRowCellStyle.cloneStyleFrom(bigTitleRowCellStyle); // 样式的克隆

        // 创建字体
        XSSFFont littleFont = workbook.createFont();
        littleFont.setFontName("宋体");
        littleFont.setFontHeightInPoints((short) 12);
        littleFont.setBold(true);
        // 把字体放入样式中
        littleTitleRowCellStyle.setFont(littleFont);

        // 内容区
        XSSFCellStyle contentRowCellStyle = workbook.createCellStyle();
        contentRowCellStyle.cloneStyleFrom(littleTitleRowCellStyle); // 样式的克隆
        contentRowCellStyle.setAlignment(HorizontalAlignment.LEFT);

        // 创建字体
        XSSFFont contentFont = workbook.createFont();
        contentFont.setFontName("宋体");
        contentFont.setFontHeightInPoints((short) 11);
        contentFont.setBold(false);
        // 把字体放入样式中
        contentRowCellStyle.setFont(contentFont);

        // 标题内容
        String[] titles = new String[]{"编号","姓名","手机号","入职日期","现住址"};
        XSSFRow row = sheet.createRow(1);
        for (int i = 0; i < titles.length; i++) {
            XSSFCell cell = row.createCell(i);
            cell.setCellValue(titles[i]);
            cell.setCellStyle(littleTitleRowCellStyle);
        }

        List<User> userList = userMapper.selectAll();
        int rowIndex = 2;
        for (User user : userList) {
            XSSFRow contentRow = sheet.createRow(rowIndex);

            XSSFCell cell = contentRow.createCell(0);
            cell.setCellStyle(contentRowCellStyle);
            cell.setCellValue(user.getId());

            XSSFCell cell2 = contentRow.createCell(1);
            cell2.setCellStyle(contentRowCellStyle);
            cell2.setCellValue(user.getUserName());

            XSSFCell cell3 = contentRow.createCell(2);
            cell3.setCellStyle(contentRowCellStyle);
            cell3.setCellValue(user.getPhone());

            XSSFCell cell4 = contentRow.createCell(3);
            cell4.setCellStyle(contentRowCellStyle);
            cell4.setCellValue(sdf.format(user.getHireDate()));

            XSSFCell cell5 = contentRow.createCell(4);
            cell5.setCellStyle(contentRowCellStyle);
            cell5.setCellValue(user.getAddress());

            rowIndex ++;
        }

        //        导出的文件名称  高版本一个流两个头
        String filename="员工数据.xlsx";
        //            设置文件的打开方式和mime类型
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader( "Content-Disposition", "attachment;filename="  + new String(filename.getBytes(),"ISO8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        workbook.write(outputStream);
    }

    public void downLoadXlsxByPoiByTemplate(HttpServletResponse response) throws Exception {
        // 获取模版的路径  springboot获取根目录方式
        File rootPath = new File(ResourceUtils.getURL("classpath:").getPath());
        File templatePath = new File(rootPath.getAbsolutePath(), "/excel_template/userList.xlsx");
        // 读取模版文件产生workbook对象，这个wookbook是一个有内容的工作簿
        XSSFWorkbook workbook = new XSSFWorkbook(templatePath);
        // 读取工作簿的第一个工作表，向工作表中放数据
        XSSFSheet sheet = workbook.getSheetAt(0);
        // 获取第二个sheet中的那个单元格中的单元格格式
        XSSFCellStyle cellStyle = workbook.getSheetAt(1).getRow(0).getCell(0).getCellStyle();
        // 处理内容
        List<User> userList = this.findAll();
        int rowIndex = 2;
        for (User user : userList) {
            XSSFRow row1 = sheet.createRow(rowIndex);
            row1.setHeightInPoints(20);  // 设置行高

            XSSFCell cell1 = row1.createCell(0);
            cell1.setCellValue(user.getId());
            cell1.setCellStyle(cellStyle);

            XSSFCell cell2 = row1.createCell(1);
            cell2.setCellValue(user.getUserName());
            cell2.setCellStyle(cellStyle);

            XSSFCell cell3 = row1.createCell(2);
            cell3.setCellValue(user.getPhone());
            cell3.setCellStyle(cellStyle);

            XSSFCell cell4 = row1.createCell(3);
            cell4.setCellValue(sdf.format(user.getHireDate()));
            cell4.setCellStyle(cellStyle);

            XSSFCell cell5 = row1.createCell(4);
            cell5.setCellValue(user.getAddress());
            cell5.setCellStyle(cellStyle);

            rowIndex ++;
        }

        workbook.removeSheetAt(1);  // 删除第二个sheet

//        导出的文件名称  高版本一个流两个头
        String filename="员工数据.xlsx";
        //            设置文件的打开方式和mime类型
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader( "Content-Disposition", "attachment;filename="  + new String(filename.getBytes(),"ISO8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        workbook.write(outputStream);
    }

    public void downLoadUserInfoWithTempalte(Long id, HttpServletResponse response) throws Exception {
// 获取模版的路径  springboot获取根目录方式
        File rootPath = new File(ResourceUtils.getURL("classpath:").getPath());
        File templatePath = new File(rootPath.getAbsolutePath(), "/excel_template/userInfo.xlsx");
        // 读取模版文件产生workbook对象，这个wookbook是一个有内容的工作簿
        XSSFWorkbook workbook = new XSSFWorkbook(templatePath);
        // 读取工作簿的第一个工作表，向工作表中放数据
        XSSFSheet sheet = workbook.getSheetAt(0);
        // 处理内容
        User user = userMapper.selectByPrimaryKey(id);
        // 向模版单元格中放数据
        // 用户名 第二行第二列
        sheet.getRow(1).getCell(1).setCellValue(user.getUserName());
        // 手机号 第3行第二列
        sheet.getRow(2).getCell(1).setCellValue(user.getPhone());
        // 生日 第四行第二列
        sheet.getRow(3).getCell(1).setCellValue(sdf.format(user.getBirthday()));
        // 工资 第五行第二列
        sheet.getRow(4).getCell(1).setCellValue(user.getSalary());
        // 入职日期 第六行第二列
        sheet.getRow(5).getCell(1).setCellValue(sdf.format(user.getHireDate()));
        // 省份 第七行第二列
        sheet.getRow(6).getCell(1).setCellValue(user.getProvince());
        // 现住址 第八行第二列
        sheet.getRow(7).getCell(1).setCellValue(user.getAddress());

        // 司龄 第六行第四列   使用公式 CONCATENATE(DATEDIF(B6,TODAY(),"Y"),"年",DATEDIF(B6,TODAY(),"YM"),"个月")
        // 也可在模版中直接配置好公式
        sheet.getRow(5).getCell(3).setCellFormula("CONCATENATE(DATEDIF(B6,TODAY(),\"Y\"),\"年\",DATEDIF(B6,TODAY(),\"YM\"),\"个月\")");


        // 城市 第七行第四列
        sheet.getRow(6).getCell(3).setCellValue(user.getCity());

        // 图片  创建一个字节输出流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        // 读取图片 放入一个带有缓冲区的图片类中
        BufferedImage bufferedImage = ImageIO.read(new File(rootPath, user.getPhoto()));
        String extName = user.getPhoto().substring(user.getPhoto().lastIndexOf(".") + 1).toUpperCase();
        // 把图片写入到了字节输出流中
        ImageIO.write(bufferedImage,extName,byteArrayOutputStream);
        // Patriarch控制图片的写入 和ClientAnchor指定图片的位置
        XSSFDrawing patriarch = sheet.createDrawingPatriarch();
        // 制定图片的位置  开始列3  开始行2  结束列 4 结束行5
        // 偏移的单位 是一个英式公式的单位  一厘米=360000
        XSSFClientAnchor anchor = new XSSFClientAnchor(0,0,0,0,2,1,4,5);

        int format = 0;
        switch (extName){
            case "JPG":
                format = XSSFWorkbook.PICTURE_TYPE_JPEG;
            case "JPEG":
                format = XSSFWorkbook.PICTURE_TYPE_JPEG;
            case "PNG":
                format = XSSFWorkbook.PICTURE_TYPE_PNG;
        }

        // 开始把图片写入到sheet制定的位置
        patriarch.createPicture(anchor,workbook.addPicture(byteArrayOutputStream.toByteArray(),format));


//        导出的文件名称  高版本一个流两个头
        String filename="员工详细数据.xlsx";
        //            设置文件的打开方式和mime类型
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader( "Content-Disposition", "attachment;filename="  + new String(filename.getBytes(),"ISO8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        workbook.write(outputStream);
    }

    public void downLoadUserInfoWithEignee(Long id, HttpServletResponse response) throws Exception {
//        获取模板的路径
        File rootPath = new File(ResourceUtils.getURL("classpath:").getPath()); //SpringBoot项目获取根目录的方式
        File templatePath = new File(rootPath.getAbsolutePath(),"/excel_template/userInfo2.xlsx");
        //        读取模板文件产生workbook对象,这个workbook是一个有内容的工作薄
        XSSFWorkbook workbook  = new XSSFWorkbook(templatePath);
        // 查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        // 这里使用引擎直接导出
        workbook = (XSSFWorkbook) ExcelExportEngine.woriteToExcel(user,workbook,user.getPhoto());
        //            导出的文件名称
        String filename="用户详细信息数据.xlsx";
        //            设置文件的打开方式和mime类型
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader( "Content-Disposition", "attachment;filename="  + new String(filename.getBytes(),"ISO8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        workbook.write(outputStream);
    }
    //导出百万数据时有两个弊端：导出时使用的是SXSSFWorkBook这个类，一个工作表sheet最多只能放1048576行数据，
    // 当我们的业务数据已超过100万了，一个sheet就不够用了，必须拆分到多个工作表
    //1、不能使用模板
    //2、不能使用太多的样式
    //也就是说导出的数据太多时必须要放弃一些。
    public void downLoadMillion(HttpServletResponse response) throws IOException {
        // 创建一个空的工作簿
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        int page = 1;
        int pageSize = 200000;
        int rowIndex = 1; //每一个工作页的行数
        int num = 0; // 总数据量
        Sheet sheet = null;
        while(true) {
            List<User> userList = this.findPage(page, pageSize);
            if(CollectionUtils.isEmpty(userList)) {
                break;
            }
            if(num % 1000000 == 0) {  // 每100w数据就重新创建新的sheet和标题
                rowIndex = 1;
                // 在工作簿中创建一个工作表
                sheet = workbook.createSheet("第"+((num/1000000)+1)+"个工作表");
                // 处理标题
                String[] titles = new String[]{"编号","姓名","手机号","入职日期","现住址"};
                // 创建标题行
                Row titleRow = sheet.createRow(0);
                for (int i = 0; i < titles.length; i++) {
                    Cell cell1 = titleRow.createCell(i);
                    cell1.setCellValue(titles[i]);
                }
            }
            // 处理内容
            for (User user : userList) {
                Row row = sheet.createRow(rowIndex);
                row.createCell(0).setCellValue(user.getId());
                row.createCell(1).setCellValue(user.getUserName());
                row.createCell(2).setCellValue(user.getPhone());
                row.createCell(3).setCellValue(sdf.format(user.getHireDate()));
                row.createCell(4).setCellValue(user.getAddress());
                rowIndex ++;
                num ++;
            }
            page ++;
        }
        //            导出的文件名称
        String filename="百万数据.xlsx";
//            设置文件的打开方式和mime类型
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader( "Content-Disposition", "attachment;filename="  + new String(filename.getBytes(),"ISO8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        workbook.write(outputStream);
    }

    public void downLoadCSV(HttpServletResponse response) {
        try{
            // 准备输出流
            ServletOutputStream outputStream = response.getOutputStream();
            //            导出的文件名称
            String filename="百万数据.csv";
//            设置文件的打开方式和mime类型
            response.setHeader( "Content-Disposition", "attachment;filename="  + new String(filename.getBytes(),"ISO8859-1"));
            response.setContentType("text/csv");
            // 创建一个用来写入到csv文件中的writer
            CSVWriter writer = new CSVWriter(new OutputStreamWriter(outputStream, "utf-8"));
            // 先写头信息
            writer.writeNext(new String[]{"编号","姓名","手机号","入职日期","现住址"});
            // 如果文件数据量比较大时，循环查询写入
            int page = 1;
            while(true) {
                List<User> userList = this.findPage(page, 200000);
                if(CollectionUtils.isEmpty(userList)) {
                    break;
                }
                for (User user : userList) {
                    writer.writeNext(new String[]{user.getId().toString(),user.getUserName(),user.getPhone(),
                            sdf.format(user.getHireDate()),user.getAddress()});
                }
                writer.flush();
                page ++;
            }
            writer.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void downloadContract(Long id, HttpServletResponse response) throws Exception{
        // 获取模版的路径  springboot获取根目录方式
        File rootPath = new File(ResourceUtils.getURL("classpath:").getPath());
        File templatePath = new File(rootPath.getAbsolutePath(), "/word_template/contract_template.docx");
        XWPFDocument word = new XWPFDocument(Files.newInputStream(templatePath.toPath()));
        // 查询当前用户
        User user = this.findById(id);
        Map<String,String> map = new HashMap<>();
        map.put("userName",user.getUserName());
        map.put("hireDate",sdf.format(user.getHireDate()));
        map.put("address",user.getAddress());
//     处理正文
        List<XWPFParagraph> paragraphs = word.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            List<XWPFRun> runs = paragraph.getRuns();
            for (XWPFRun run : runs) {
                String text = run.getText(0);
                for (String key : map.keySet()) {
                    if(text.contains(key)) {
                        run.setText(text.replaceAll(key,map.get(key)),0);
                    }
                }
            }
        }
        // 处理表格
        List<Resource> resourceList = user.getResourceList();
        XWPFTable xwpfTable = word.getTables().get(0);
        XWPFTableRow row = xwpfTable.getRow(0);
        int rowIndex = 1;
        for (Resource resource : resourceList) {
            // 添加行
            copyRow(xwpfTable,row,rowIndex);
            XWPFTableRow row1 = xwpfTable.getRow(rowIndex);
            row1.getCell(0).setText(resource.getName());
            row1.getCell(1).setText(resource.getPrice().toString());
            row1.getCell(2).setText(resource.getNeedReturn()?"需求":"不需要");

            File imageFile = new File(rootPath,"/static"+resource.getPhoto());
            setCellImage(row1.getCell(3),imageFile);
            rowIndex++;
        }


        String filename="员工合同.docx";
//            设置文件的打开方式和mime类型
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader( "Content-Disposition", "attachment;filename="  + new String(filename.getBytes(),"ISO8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        word.write(outputStream);
    }

    private void setCellImage(XWPFTableCell cell, File imageFile) {
        XWPFRun run = cell.getParagraphs().get(0).createRun();
        //        InputStream pictureData, int pictureType, String filename, int width, int height
        try(FileInputStream inputStream = new FileInputStream(imageFile)) {
            run.addPicture(inputStream,XWPFDocument.PICTURE_TYPE_JPEG,imageFile.getName(), Units.toEMU(100),Units.toEMU(50));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void copyRow(XWPFTable xwpfTable, XWPFTableRow sourceRow, int rowIndex) {
        XWPFTableRow targetRow = xwpfTable.insertNewTableRow(rowIndex);
        targetRow.getCtRow().setTrPr(sourceRow.getCtRow().getTrPr());
        //        获取源行的单元格
        List<XWPFTableCell> cells = sourceRow.getTableCells();
        if(CollectionUtils.isEmpty(cells)){
            return;
        }
        XWPFTableCell targetCell = null;
        for (XWPFTableCell cell : cells) {
            targetCell = targetRow.addNewTableCell();
            //            附上单元格的样式
            //            单元格的属性
            targetCell.getCTTc().setTcPr(cell.getCTTc().getTcPr());
            targetCell.getParagraphs().get(0).getCTP().setPPr(cell.getParagraphs().get(0).getCTP().getPPr());
        }
    }

    public void downLoadXlsxWithEayPoi(HttpServletRequest request, HttpServletResponse response) throws Exception{
        // 查询用户数据
        List<User> userList = userMapper.selectAll();
        // 指定导出的格式是高版本的格式
        ExportParams exportParams = new ExportParams("员工信息", "数据", ExcelType.XSSF);
        // 直接使用EasyPoi提供的方式
        org.apache.poi.ss.usermodel.Workbook workbook = ExcelExportUtil.exportExcel(exportParams, User.class, userList);

        String filename="员工信息.xlsx";
//            设置文件的打开方式和mime类型
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader( "Content-Disposition", "attachment;filename="  + new String(filename.getBytes(),"ISO8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        workbook.write(outputStream);
    }
}
